<?php
ini_set('max_execution_time', -1);
ini_set('memory_limit','1024M');
error_reporting(E_ERROR | E_PARSE);

function GetBetween($content,$start,$end){
    $r = explode($start, $content);
    if (isset($r[1])){
        $r = explode($end, $r[1]);
        return $r[0];
    }
    return '';
}

function parsejson ( $url ){
	//load VDF data either from API call or fetching from file/url
    //no matter your method, $json must contain the VDF data to be parsed
    $json = file_get_contents( $url );
 
    //encapsulate in braces
    $json = "{\n$json\n}";
 
    //replace open braces
    $pattern = '/"([^"]*)"(\s*){/';
    $replace = '"${1}": {';
    $json = preg_replace($pattern, $replace, $json);
 
    //replace values
    $pattern = '/"([^"]*)"\s*"([^"]*)"/';
    $replace = '"${1}": "${2}",';
    $json = preg_replace($pattern, $replace, $json);
 
    //remove trailing commas
    $pattern = '/,(\s*[}\]])/';
    $replace = '${1}';
    $json = preg_replace($pattern, $replace, $json);
 
    //add commas
    $pattern = '/([}\]])(\s*)("[^"]*":\s*)?([{\[])/';
    $replace = '${1},${2}${3}${4}';
    $json = preg_replace($pattern, $replace, $json);
 
    //object as value
    $pattern = '/}(\s*"[^"]*":)/';
    $replace = '},${1}';
    $json = preg_replace($pattern, $replace, $json);
    return $json;
}

function calculateprice($market_price)
{
	$price = 0;

	if($market_price < 0.5)
	{
		$price = 10000;
	}
	else if($market_price >= 0.5 && $market_price < 0.7)
	{
		$price = 15000;
	}
	else if($market_price >= 0.7 && $market_price < 0.8)
	{
		$price = 20000;
	}
	else if($market_price >= 0.8 && $market_price < 0.9)
	{
		$price = 30000;
	}
	else if($market_price >= 0.9 && $market_price < 1.2)
	{
		$price = 30000;
	}
	else if($market_price >= 1.2 && $market_price < 1.7)
	{
		$price = 40000;
	}
	else
	{
		$i=1;

		for( $price1 = 1.7; $price1 < $market_price - 0.5 ; $price1 = $price1 + 0.5)
		{
		   $i = $i + 1;
		}

		$price=40000 + $i*10000;
	}

	return $price;
}

function getprice ( $itemname ){
	$url2 = 'http://steamcommunity.com/market/priceoverview/?appid=570&market_hash_name='.urlencode( $itemname ); 
	$data_json2 = file_get_contents ( $url2 );
	$data_array2 = json_decode ( $data_json2, true );

	if( isset($data_array2['lowest_price']) )
	{
		$price=$data_array2['lowest_price'];
		$price1 = $price;
		unset($price);
		echo "<br/> Get Item Price Success";
		return $price1;
	}

	return null;
}

$url = 'http://api.steampowered.com/IEconItems_570/GetSchema/v0001/?key=3DFB8CA4E10DF4D49A942D2524A3BE9A';
$data_json = file_get_contents ( $url );
$data_array = json_decode( $data_json, true );

print_r($data_array['result']['items_game_url']);
$url1 = $data_array['result']['items_game_url'];
$data_json1 = parsejson( $url1 );
$data_array1 = json_decode( $data_json1, true );

echo "<br/> Get all data success";

$a = array();
$b = array();
$y = array();
$z = array();

foreach ($data_array['result']['item_sets'] as $g => $h)
{
	$y['set_item_name'] = $h['item_set'];
	$y['set_item_quantity'] = count($h['items']);
	if(count($y) == 2)
	{
		$z[] = $y;
		unset($y);
		echo "<br/> Fetch Set Items success";
	}
}

foreach ($data_array['result']['items'] as $k => $v)
{
	if($v['item_quality'] == 1 || $v['item_quality'] == 2 || $v['item_quality'] == 4 || $v['item_quality'] == 15 || $v['item_quality'] == 17 || $v['item_quality'] == 18 || $v['item_quality'] == 19)
	{
		if( isset($v['tool']) )
		{
			if( ($v['tool']['type'] == "supply_crate" && $v['tool']['restriction'] == "no_key" ) || $v['tool']['type'] == "league_view_pass" || $v['tool']['type'] == "item_pack"  )
			{
				
				$a['name'] 			= $v['name'];
				$a['image'] 		= $v['image_url_large'];
				$a['item_set']  	= $v['item_set'];

				$a['price']			= getprice( $v['name'] );

				$a['quality'] 		= $data_array1['items_game']['items'][ $v['defindex'] ]['item_quality'];
				$a['add_date'] 		= $data_array1['items_game']['items'][ $v['defindex'] ]['creation_date'];
				$a['type']			= $data_array1['items_game']['items'][ $v['defindex'] ]['prefab'];

				if( !is_null($a['price']) )
				{
					$a['price'] = substr($a['price'], 5);
				}

				$a['pricevn'] = calculateprice($a['price']);

				if(is_null( $data_array1['items_game']['items'][ $v['defindex'] ]['item_rarity'] ))
				{
					$a['item_rarity'] 	= 'none';
				}
				else
				{
					$a['item_rarity'] 	= $data_array1['items_game']['items'][ $v['defindex'] ]['item_rarity'];
				}
				
				$q 		 = array_keys($data_array1['items_game']['items'][ $v['defindex'] ]['used_by_heroes']);
				if (substr($q[0], 14) == '')
				{
					$a['hero'] = 'All heroes';
				}
				else
				{
					$a['hero'] = substr($q[0], 14);
				}
				
				
				if(count($a) == 9)
				{
					$b[] = $a;
					unset($a);
					echo "<br/> Fetch Item success";
				}
			}
		}
		else
		{
			$a['name'] 			= $v['name'];
				$a['image'] 		= $v['image_url_large'];
				$a['item_set']  	= $v['item_set'];

				$a['price']			= getprice( $v['name'] );

				$a['quality'] 		= $data_array1['items_game']['items'][ $v['defindex'] ]['item_quality'];
				$a['add_date'] 		= $data_array1['items_game']['items'][ $v['defindex'] ]['creation_date'];
				$a['type']			= $data_array1['items_game']['items'][ $v['defindex'] ]['prefab'];

				if( !is_null($a['price']) )
				{
					$a['price'] = substr($a['price'], 5);
				}

				$a['pricevn'] = calculateprice($a['price']);

				if(is_null( $data_array1['items_game']['items'][ $v['defindex'] ]['item_rarity'] ))
				{
					$a['item_rarity'] 	= 'none';
				}
				else
				{
					$a['item_rarity'] 	= $data_array1['items_game']['items'][ $v['defindex'] ]['item_rarity'];
				}
				
				$q 		 = array_keys($data_array1['items_game']['items'][ $v['defindex'] ]['used_by_heroes']);
				if (substr($q[0], 14) == '')
				{
					$a['hero'] = 'All heroes';
				}
				else
				{
					$a['hero'] = substr($q[0], 14);
				}
				
				
				if(count($a) == 9)
				{
					$b[] = $a;
					unset($a);
					echo "<br/> Fetch Item success";
				}
		}
	}
}

echo "<br/> Fetch all data success";

$username = 'root';
$password = '';
try {
    $conn = new PDO('mysql:host=localhost;dbname=dota2shopvn', $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    foreach($z as $n => $m) {
    	$set_item_name	= $m['set_item_name'];
    	$set_item_quantity = $m['set_item_quantity'];

    	$stmt = $conn->prepare('select SET_ITEMS_NAME from set_items where SET_ITEMS_NAME = ?');
    	$stmt->bindParam(1, $set_item_name);
    	$stmt->execute();
    	$result_set_item = $stmt->fetchAll();

    	if(is_null($result_set_item[0]))
    	{
    		$stmt = $conn->prepare('insert into set_items values (?, ?)');
    		$stmt->bindParam(1, $set_item_name);
    		$stmt->bindParam(2, $set_item_quantity);
    		if($stmt->execute() == false) {
	    		throw new Exception(print_r($stmt->errorInfo(),1).PHP_EOL.$sql);
	    	}
	    	echo "<br/> Insert Set Items Success";
    	}
    	else
    	{
    		echo "<br/> Update Set Items Name : " . $set_item_name;
			$stmt = $conn->prepare('update set_items set SET_ITEMS_NAME = ?, QUANTITY_OF_SET = ? where SET_ITEMS_NAME = ?');
    		$stmt->bindParam(1, $set_item_name);
    		$stmt->bindParam(2, $set_item_quantity);
    		$stmt->bindParam(3, $set_item_name);
    		if($stmt->execute() == false) {
	    		throw new Exception(print_r($stmt->errorInfo(),1).PHP_EOL.$sql);
	    	}
	    	echo "<br/> Update Set Items Success";
    	}
    }

    foreach($b as $c => $d) {
    	$stmt = $conn->prepare('select ITEM_ID, ITEM_NAME from item where ITEM_NAME = ?');
		$name = $d['name'];
	    $stmt->bindParam(1, $name);
		$stmt->execute();
		$result=$stmt->fetchAll();

		if(is_null($result[0]))
		{
			$stmt = $conn->prepare('insert into item (ITEM_ID, ITEM_NAME, ITEM_RARITY, ITEM_QUALITY, ITEM_IMAGE, HERO_NAME, SET_ITEMS_NAME, PRICE_MARKET, ITEM_TYPE, ADD_DATE, PRICEVN) values (DEFAULT,?,?,?,?,?,?,?,?,?)');
	    	$name		= $d['name'];
	    	$item_rarity = $d['item_rarity'];
	    	$quality 	= $d['quality'];
	    	$image 		= $d['image'];
	    	$hero		= $d['hero'];
	    	$item_set	= $d['item_set'];
	    	$price 		= $d['price'];
	    	$type 		= $d['type'];
	    	$add_date	= $d['add_date'];
	    	$pricevn 	= $d['pricevn'];


	    	$stmt->bindParam(1, $name);
	    	$stmt->bindParam(2, $item_rarity);
	    	$stmt->bindParam(3, $quality);
	    	$stmt->bindParam(4, $image);
	    	$stmt->bindParam(5, $hero);
	    	$stmt->bindParam(6, $item_set);
	    	$stmt->bindParam(7, $price);
	    	$stmt->bindParam(8, $type);
	    	$stmt->bindParam(9, $add_date);
	    	$stmt->bindParam(10, $pricevn);

	    	if($stmt->execute() == false) {
	    		throw new Exception(print_r($stmt->errorInfo(),1).PHP_EOL.$sql);
	    	}
	    	echo "<br/> Insert Item Success";

		}
		else
		{
			echo "<br/> Update item id : " . $result[0]['ITEM_ID'];
			$stmt = $conn->prepare('update item set ITEM_NAME = ?, ITEM_RARITY = ?, ITEM_QUALITY = ?, ITEM_IMAGE = ?, HERO_NAME = ?, SET_ITEMS_NAME = ?, PRICE_MARKET = ?, ITEM_TYPE = ?, ADD_DATE = ?, PRICEVN = ? where ITEM_ID = ?');
			$id 		= $result[0]['ITEM_ID'];
	    	$name		= $d['name'];
	    	$item_rarity = $d['item_rarity'];
	    	$quality 	= $d['quality'];
	    	$image 		= $d['image'];
	    	$hero		= $d['hero'];
	    	$item_set	= $d['item_set'];
	    	$price 		= $d['price'];
	    	$type		= $d['type'];
	    	$add_date	= $d['add_date'];
	    	$pricevn 	= $d['pricevn'];

	    	$stmt->bindParam(1, $name);
	    	$stmt->bindParam(2, $item_rarity);
	    	$stmt->bindParam(3, $quality);
	    	$stmt->bindParam(4, $image);
	    	$stmt->bindParam(5, $hero);
	    	$stmt->bindParam(6, $item_set);
	    	$stmt->bindParam(7, $price);
	    	$stmt->bindParam(8, $type);
	    	$stmt->bindParam(9, $add_date);
	    	$stmt->bindParam(10, $pricevn);
	    	$stmt->bindParam(11, $id);

	    	if($stmt->execute() == false) {
	    		throw new Exception(print_r($stmt->errorInfo(),1).PHP_EOL.$sql);
	    	}
	    	echo "<br/> Update Item Success";

		}
    }
	$stmt = $conn->prepare('CALL updatename');
    $stmt->execute();
	$stmt = $conn->prepare('delete from item where PRICE_MARKET is NULL');
	$stmt->execute();
    echo "<br/> Insert / Update all success";
}
catch(PDOException $ex) {
    echo "An Error occured!"; //user friendly message
    echo $ex->getMessage();
    
}
	echo "<br/> Complete all";
?>